package api

import (
	"aglaia/global"
	"aglaia/internal/service"
	"aglaia/pkg/app"
	"aglaia/pkg/errcode"
	"github.com/gin-gonic/gin"
)

func FirstOrCreateTag(c *gin.Context) {
	param := service.FirstOrCreateTagRequest{}
	response := app.NewResponse(c)
	if err := response.Bind(&param); err != nil {
		global.Logger.Infof("response.Bind err: %v\n", err)
		response.ToErrorResponse(errcode.InvalidParams)
		return
	}

	svc := service.New(c)
	tag, err := svc.FirstOrCreateTag(param)
	if err != nil {
		global.Logger.Infof("svc.FirstOrCreateTag err: %v\n", err)
		response.ToErrorResponse(errcode.ServerError)
		return
	}

	response.ToResponse(gin.H{
		"tag": tag,
	})
}

func DeleteTag(c *gin.Context) {
	param := service.DeleteTagRequest{}
	response := app.NewResponse(c)
	if err := response.Bind(&param); err != nil {
		global.Logger.Infof("response.Bind err: %v\n", err)
		response.ToErrorResponse(errcode.InvalidParams)
		return
	}

	svc := service.New(c)
	if err := svc.DeleteTag(param); err != nil {
		global.Logger.Infof("svc.FirstOrCreateTag err: %v\n", err)
		response.ToErrorResponse(errcode.ServerError)
		return
	}

	response.ToResponse(nil)
}

func Tags(c *gin.Context) {
	response := app.NewResponse(c)

	svc := service.New(c)
	tags, err := svc.Tags()
	if err != nil {
		global.Logger.Infof("svc.FirstOrCreateTag err: %v\n", err)
		response.ToErrorResponse(errcode.ServerError)
		return
	}

	response.ToResponseList(tags, len(tags))
}
